/*
* 生产配置
* */

import 'package:center_beijing/common/enums.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:flutter/material.dart';
import 'package:center_beijing/api/component_api.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/custom_floatingAction_buttonLocation.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/search_widget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_pickers/pickers.dart';

class ProductSetting extends StatefulWidget {
  @override
  _ProductSettingState createState() => _ProductSettingState();
}

class _ProductSettingState extends State<ProductSetting> {
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  EasyRefreshController _controller = EasyRefreshController();
  List<SelectItems> typeList = [
    SelectItems(label: '全部状态', value: ''),
    SelectItems(label: '待生产', value: '1'),
    SelectItems(label: '生产中', value: '2'),
    SelectItems(label: '已完成', value: '3'),
    SelectItems(label: '已入库', value: '4'),
    SelectItems(label: '已运输', value: '5')
  ];
  SelectItems selectType = SelectItems(label: '全部状态', value: '');
  List<SelectItems> taskList = [];
  SelectItems selectTask = SelectItems(label: '全部任务', value: '');
  var selectBuild = '';
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;

  @override
  void initState() {
    super.initState();
    this.getAllTask();
    bus.on('refreshProductSetting', (arg) {
      page = 1;
      // _controller.finishLoad(success: true, noMore: false);
      this.getInfoList();
    });
  }

  getAllTask() async {
    var result = await getProjectTasks(GlobalConfig.selectFactory.value);
    List<SelectItems> list = [];
    if (result != null && result.length > 0) {
      for (var item in result) {
        list.add(SelectItems(label: item['taskCode'], value: item['id']));
      }
      list.insert(0, SelectItems(label: '全部任务', value: ''));
      this.setState(() {
        taskList = list;
        this.getInfoList();
      });
    } else {
      this.setState(() {
        firstLoad = false;
      });
    }
    LogUtil.d(result);
  }

  getInfoList() async {
    var pass = {
      'dayPlanId': selectTask.value,
      'page': page,
      'page-size': pageSize,
      'projectId': GlobalConfig.selectFactory.value,
      'isPc': true,
      'processStatus': selectType.value,
      'chargePersonId':GlobalConfig.userInfo['userId']
    };
    var result = await getTasksList(pass);
    loading.dismiss();
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null) {
      if (result['data'].length == 0) {
        // _controller.finishLoad(success: true, noMore: true);
      } else {
        dataSource.addAll(result['data']);
      }
    }
    this.setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('生产配置'),
        ),
        body: SafeArea(
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 70),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.fromLTRB(Styles.spacing16,
                      Styles.spacing4, Styles.spacing16, Styles.spacing4),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Container(
                          color: Colors.white,
                          child: PullSelectWidget(
                            text_align: TextAlign.center,
                            rightText: selectTask.label,
                            backColor: Colors.white,
                            items: taskList,
                            selectCallback: (value) {
                              this.selectTask = value;
                              page = 1;
                              loading.show(delay: 15);
                              this.getInfoList();
                            },
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          color: Colors.white,
                          child: PullSelectWidget(
                            text_align: TextAlign.center,
                            rightText: selectType.label,
                            backColor: Colors.white,
                            items: typeList,
                            selectCallback: (value) {
                              this.selectType = value;
                              page = 1;
                              loading.show(delay: 15);
                              this.getInfoList();
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                    child: NotificationListener(
                  onNotification: (_) {
                    FocusScope.of(context).requestFocus(new FocusNode());
                    return false;
                  },
                  child: this.dataSource.length > 0
                      ? EasyRefresh.custom(
                          shrinkWrap: true,
                          firstRefresh: false,
                          controller: _controller,
                          header: MaterialHeader(),
                          footer: ClassicalFooter(
                              loadingText: '加载中',
                              loadText: '上拉加载',
                              noMoreText: '没有更多数据',
                              loadedText: '加载完成',
                              infoText: '更新于 %T',
                              textColor: Styles.NoMoreColor,
                              showInfo: false),
                          emptyWidget: (dataSource.length == 0 && !firstLoad)
                              ? Center(
                                  child: Image(
                                    image:
                                        AssetImage('assets/images/no_data.png'),
                                    width: 128,
                                    height: 150,
                                  ),
                                )
                              : null,
                          onRefresh: () async {
                            // _controller.finishLoad(success: true, noMore: false);
                            if (mounted) {
                              page = 1;
                              this.getInfoList();
                            }
                          },
                          onLoad: () async {
                            await Future.delayed(Duration(seconds: 2), () {
                              if (mounted) {
                                page++;
                                this.getInfoList();
                              }
                            });
                          },
                          slivers: <Widget>[
                              SliverList(
                                delegate: SliverChildBuilderDelegate(
                                  (context, index) {
                                    return GestureDetector(
                                      onTap: () {
                                        this.setState(() {
                                          this.dataSource[index]['selected'] =
                                          !(this.dataSource[index]
                                          ['selected'] !=
                                              null &&
                                              this.dataSource[index]
                                              ['selected']);
                                        });
                                      },
                                      child: Container(
                                        color: Colors.white,
                                        padding: EdgeInsets.fromLTRB(
                                            Styles.spacing8,
                                            0,
                                            Styles.spacing8,
                                            0),
                                        child: Row(
                                          children: [
                                            Image(
                                              image: AssetImage((this.dataSource[
                                              index]
                                              ['selected'] !=
                                                  null &&
                                                  this.dataSource[index]
                                                  ['selected'])
                                                  ? "assets/images/checkbox_normal.png"
                                                  : "assets/images/checkbox_selected.png"),
                                              width: 20.w,
                                              height: 20.h,
                                            ),
                                            Expanded(
                                                child: Container(
                                                  color: Colors.white,
                                                  padding: EdgeInsets.fromLTRB(
                                                      Styles.spacing8,
                                                      Styles.spacing8,
                                                      Styles.spacing16,
                                                      Styles.spacing8),
                                                  margin: EdgeInsets.fromLTRB(
                                                      Styles.spacing8,
                                                      Styles.spacing4,
                                                      Styles.spacing8,
                                                      Styles.spacing4),
                                                  child: Row(
                                                    children: [
                                                      Expanded(
                                                        child: Column(
                                                          crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                          children: [
                                                            Row(
                                                              children: [
                                                                Expanded(
                                                                    child: Column(
                                                                      crossAxisAlignment:
                                                                      CrossAxisAlignment
                                                                          .start,
                                                                      children: [
                                                                        Text(
                                                                          this.dataSource[index]
                                                                          [
                                                                          'code'] !=
                                                                              null
                                                                              ? this.dataSource[
                                                                          index]
                                                                          [
                                                                          'code']
                                                                              : '--',
                                                                          style: TextStyle(
                                                                              color: Styles
                                                                                  .DetailColor,
                                                                              fontSize:
                                                                              Styles
                                                                                  .Middle15Font),
                                                                        ),
                                                                        Text(
                                                                          this.dataSource[index]
                                                                          [
                                                                          'compKind'] !=
                                                                              null
                                                                              ? this.dataSource[index]
                                                                          [
                                                                          'compKind']
                                                                          [
                                                                          'compKindName']
                                                                              : '--',
                                                                          style: TextStyle(
                                                                              color: Styles
                                                                                  .DetailColor,
                                                                              fontSize:
                                                                              Styles
                                                                                  .Middle15Font),
                                                                        ),
                                                                      ],
                                                                    )),
                                                                Row(
                                                                  children: [
                                                                    Container(
                                                                      color: Styles
                                                                          .BlueColor,
                                                                      margin: EdgeInsets
                                                                          .fromLTRB(
                                                                          Styles
                                                                              .spacing4,
                                                                          0,
                                                                          Styles
                                                                              .spacing4,
                                                                          0),
                                                                      padding: EdgeInsets.fromLTRB(
                                                                          Styles
                                                                              .spacing4,
                                                                          Styles
                                                                              .spacing4,
                                                                          Styles
                                                                              .spacing4,
                                                                          Styles
                                                                              .spacing4),
                                                                      child: Text(
                                                                        (this.dataSource[index]['state'] !=
                                                                            null &&
                                                                            this.dataSource[index]['state'] ==
                                                                                2)
                                                                            ? '维修中'
                                                                            : '正常',
                                                                        style: TextStyle(
                                                                            color: Colors
                                                                                .white,
                                                                            fontSize:
                                                                            Styles.SmallFont),
                                                                      ),
                                                                    ),
                                                                    Container(
                                                                      color: StatusType.getOperationColor(this.dataSource[index]['processStatus']),
                                                                      margin: EdgeInsets
                                                                          .fromLTRB(
                                                                          Styles
                                                                              .spacing4,
                                                                          0,
                                                                          Styles
                                                                              .spacing4,
                                                                          0),
                                                                      padding: EdgeInsets.fromLTRB(
                                                                          Styles
                                                                              .spacing4,
                                                                          Styles
                                                                              .spacing4,
                                                                          Styles
                                                                              .spacing4,
                                                                          Styles
                                                                              .spacing4),
                                                                      child: Text(
                                                                        this.dataSource[index]['processStatus'] !=
                                                                            null
                                                                            ? productType.getType(this.dataSource[index]['processStatus'])
                                                                            : '未知',
                                                                        style: TextStyle(
                                                                            color: Colors
                                                                                .white,
                                                                            fontSize:
                                                                            Styles.SmallFont),
                                                                      ),
                                                                    )
                                                                  ],
                                                                )
                                                              ],
                                                            ),
                                                            Text(
                                                              this.dataSource[index]
                                                              [
                                                              'orderInfo'] !=
                                                                  null
                                                                  ? this.dataSource[
                                                              index]
                                                              [
                                                              'orderInfo']
                                                              ['orderName']
                                                                  : '--',
                                                              style: TextStyle(
                                                                  color: Styles
                                                                      .LeftTitleColor,
                                                                  fontSize: Styles
                                                                      .NormalFont),
                                                            ),
                                                            Text(
                                                              "实际配合比 ${this.dataSource[
                                                              index]
                                                              [
                                                              'mixProportion']!=null?this.dataSource[
                                                              index]
                                                              [
                                                              'mixProportion']
                                                              ['name']??'--':'--'}",
                                                              style: TextStyle(
                                                                  color: Styles
                                                                      .LeftTitleColor,
                                                                  fontSize: Styles
                                                                      .NormalFont),
                                                            ),
                                                            Text(
                                                              "方量 ${this.dataSource[
                                                              index]
                                                              [
                                                              'concreteUsage']??'--'}",
                                                              style: TextStyle(
                                                                  color: Styles
                                                                      .LeftTitleColor,
                                                                  fontSize: Styles
                                                                      .NormalFont),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ))
                                          ],
                                        ),
                                      ),
                                    );
                                  },
                                  childCount: dataSource.length,
                                ),
                              ),
                            ])
                      : firstLoad
                          ? Center(
                              child: CircularProgressIndicator(),
                            )
                          : Center(
                              child: Image(
                                image: AssetImage('assets/images/no_data.png'),
                                width: 128,
                                height: 150,
                              ),
                            ),
                ))
              ],
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          color: Colors.white,
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Row(
            children: [
              Expanded(
                  flex: 1,
                  child: Container(
                    decoration: new BoxDecoration(
                      border: Border.all(width: 1, color: Styles.BlueColor),
                      //背景
                      color: Styles.LightBlueColor,
                      //设置四周圆角 角度
                      borderRadius: BorderRadius.all(Radius.circular(12.0)),
                    ),
                    margin: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: FlatButton(
                        onPressed: () {
                          var tem;
                          List list = [];
                          for(var i=0;i<this.dataSource.length;i++){
                            if(this.dataSource[i]['selected']!=null&&this.dataSource[i]['selected']){
                              list.add(this.dataSource[i]);
                              if(tem!=null){
                                if(!(this.dataSource[i]['mixProportion']!=null)){
                                  Fluttertoast.showToast(msg: '选中构件设计配合比不能为空');
                                  return;
                                } else if(this.dataSource[i]['mixProportion']['id'] != tem['mixProportion']['id']){
                                  Fluttertoast.showToast(msg: '选中构件设计配合比必须相同');
                                  return;
                                }
                              }
                              tem = this.dataSource[i];
                            }
                          }
                          if(list.length==0){
                            Fluttertoast.showToast(msg: '请选择构件');
                            return;
                          }
                        Get.toNamed(RouteConfig.mixProportion,arguments: list);
                        },
                        child: Container(
                          height: Styles.MainButtonHeight,
                          alignment: Alignment.center,
                          child: Text('设置实际配合比',
                              style: TextStyle(
                                  color: Styles.BlueColor,
                                  fontSize: Styles.Middle16Font)),
                        )),
                  )),
              Expanded(
                  flex: 1,
                  child: Container(
                    decoration: new BoxDecoration(
                      border: Border.all(width: 1, color: Styles.BlueColor),
                      //背景
                      color: Styles.LightBlueColor,
                      //设置四周圆角 角度
                      borderRadius: BorderRadius.all(Radius.circular(12.0)),
                    ),
                    margin: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: FlatButton(
                        onPressed: () async {
                          List list = [];
                          for(var i=0;i<this.dataSource.length;i++){
                            if(this.dataSource[i]['selected']!=null&&this.dataSource[i]['selected']){
                              list.add(this.dataSource[i]);

                            }
                          }
                          if(list.length==0){
                            Fluttertoast.showToast(msg: '请选择构件');
                            return;
                          }
                         var result = await Get.toNamed(RouteConfig.squareQuantity,arguments: list);
                          if(result!=null){
                            page = 1;
                            this.getInfoList();
                          }
                        },
                        child: Container(
                          height: Styles.MainButtonHeight,
                          alignment: Alignment.center,
                          child: Text('设置方量',
                              style: TextStyle(
                                  color: Styles.BlueColor,
                                  fontSize: Styles.Middle16Font)),
                        )),
                  )),

            ],
          ),
        ));
  }
}

